const express = require("express");
const router = express.Router();
const moment = require("moment");
var mysql = require("mysql");
const env = {
  host: "111.231.22.97",
  user: "wangs-web",
  password: "HsTjw82zF7f6fjWY",
  database: "wangs-web", //数据库名字
};

const other = require("./other");
router.use(other);

//过滤
const filters = (e) => {
  let objs = {};
  for (let keys in e) {
    if (e[keys] != "" && e[keys] != undefined && e[keys] != null) {
      objs[keys] = e[keys];
    }
  }
  return Object.keys(objs);
};

const fit = (arr, arrs) => {
  arr.forEach((ele) => {
    ele.memberStr = "";
    ele.memberArr.forEach((els, ind) => {
      arrs.forEach((elk) => {
        if (els == elk.id) {
          if (ind != ele.memberArr.length - 1) {
            ele.memberStr += elk.name + ",";
          } else {
            ele.memberStr += elk.name;
          }
        }
      });
    });
  });
  return arr;
};

const userlist = () => {
  return new Promise((reslove, reject) => {
    let pools = mysql.createPool(env);
    let sql = "select * from userlist";
    pools.query(sql, (err, result) => {
      if (err) throw err;
      reslove(result);
    });
  });
};

const member = (req, res) => {
  const arrs = filters(req.query);
  let pageNo = Number(req.query["pageNo"]);
  let pageSize = Number(req.query["pageSize"]);
  let offset = (pageNo - 1) * pageSize;
  console.log(arrs, "arrs");
  /* pageNo,pageSize,id,role */
  if (arrs.length == 4) {
    let pools = mysql.createPool(env);
    let sql = "select * from dtotallist";
    let queryArr = [req.query.id];
    pools.query(sql, queryArr, async (err, result) => {
      if (err) throw err;
      let res1 = [];
      result.forEach((ele) => {
        if (ele.member.indexOf(req.query.id) != -1) {
          ele.memberArr = ele.member.split("/");
          res1.push(ele);
        }
      });
      let data = await userlist();
      const yy = fit(res1, data);
      res.send({
        code: 200,
        msg: "success",
        data: {
          data: yy.slice(offset, pageSize * pageNo),
          total: yy.length,
        },
      });
    });
  } else {
    let target = filters(req.query).filter((res) => {
      return (
        res != "pageNo" && res != "pageSize" && res != "id" && res != "role"
      );
    });
    let sql = "select * from dtotallist where ";
    let pools = mysql.createPool(env);
    let queryArr = [];
    target.forEach((el, index) => {
      if (index != target.length - 1) {
        sql += el + " = ? and";
        queryArr.push(req.query[`${el}`]);
      } else {
        sql += el + " = ? ";
        queryArr.push(req.query[`${el}`]);
      }
    });
    pools.query(sql, queryArr, async (err, result) => {
      if (err) throw err;
      let res1 = [];
      result.forEach((ele) => {
        if (ele.member.indexOf(req.query.id) != -1) {
          ele.memberArr = ele.member.split("/");
          res1.push(ele);
        }
      });
      let data = await userlist();
      const yy = fit(res1, data);
      res.send({
        code: 200,
        msg: "success",
        data: {
          data: yy.slice(offset, pageNo * pageSize),
          total: yy.length,
        },
      });
    });
  }
};

const admin = (req, res) => {
  const arrs = filters(req.query);
  let pageNo = Number(req.query["pageNo"]);
  let pageSize = Number(req.query["pageSize"]);
  let offset = (pageNo - 1) * pageSize;
  if (arrs.length == 3) {
    console.log("全部查询");
    let sql = "select * from dtotallist limit ?,?";
    let sqls = "select count(*) from dtotallist";
    let pools = mysql.createPool(env);
    pools.query(sql, [offset, pageSize], (err, result) => {
      if (err) {
        console.log(err);
        res.status(500);
        res.send({
          code: 500,
          msg: "error",
        });
      } else {
        pools.query(sqls, (err, resl) => {
          if (err) {
            res.send({
              code: 500,
              msg: "error",
            });
          } else {
            let total = resl[0]["count(*)"];
            res.send({
              code: 200,
              msg: "success",
              data: {
                data: result,
                total: total,
              },
            });
          }
        });
      }
    });
  } else {
    let target = filters(req.query).filter((res) => {
      return res != "pageNo" && res != "pageSize" && res != "role";
    });
    let sqls = "select * from dtotallist where ";
    let pools = mysql.createPool(env);
    let queryArr = [];
    target.forEach((el, index) => {
      if (index != target.length - 1) {
        sqls += el + " = ? and";
        queryArr.push(req.query[`${el}`]);
      } else {
        sqls += el + " = ? ";
        queryArr.push(req.query[`${el}`]);
      }
    });
    pools.query(sqls, queryArr, async (err, resk) => {
      if (err) throw err;
      resk.forEach((ele) => {
        ele.memberArr = ele.member.split("/");
      });
      let data = await userlist();
      const yy = fit(resk, data);
      res.send({
        code: 200,
        msg: "success",
        data: {
          data: yy,
          total: yy.length,
        },
      });
    });
  }
};

//查询日报列表(员工或管理员)
router.get("/getDailyAll", (req, res) => {
  if (req.query.id && req.query.role == 0) {
    member(req, res);
  } else {
    admin(req, res);
  }
});

//新增由点击操作完成

//查询我的日报信息
router.get("/getmddetail", (req, res) => {
  let sql = "select * from ddetaillist where projectCode = ? and name = ?";
  let pools = mysql.createPool(env);
  console.log(req.query.name, "ppp");
  pools.query(sql, [req.query.projectCode, req.query.name], (err, result) => {
    if (err) {
      res.status(500);
    } else {
      res.send({
        code: 200,
        msg: "success",
        data: {
          data: result,
        },
      });
    }
  });
});
//新增我的日报
const indexs = () => {
  let str = "";
  for (let i = 0; i < 10; i++) {
    let ind = Math.ceil(Math.random() * 10);
    str += ind + 1;
  }
  return str;
};

//判断个人是否还需要填写
const deterPerson = (req) => {
  return new Promise((resolve, reject) => {
    var mtotals;
    let sql = "select * from dtotallist where projectCode = ?";
    let sqls = "select * from ddetaillist where projectCode = ? and name = ?";
    let pools = mysql.createPool(env);
    pools.query(sql, [req.body.projectCode], (err, result) => {
      if (err) {
        console.log(err);
      } else {
        mtotals = Number(result[0]["mtotals"]);
        pools.query(
          sqls,
          [req.body.projectCode, req.body.name],
          (err, resk) => {
            if (err) {
              console.log(err);
            } else {
              if (mtotals == resk.length) {
                // res.send({
                //   code: 500,
                //   msg: "日报已填满",
                // });
                resolve(false);
              } else {
                //继续
                // deterDate(req, res);
                resolve(true);
              }
            }
          }
        );
      }
    });
  });
};

//判断这个人当前日期是否填写过
const deterDate = (req) => {
  return new Promise((resolve, reject) => {
    let pools = mysql.createPool(env);
    let { projectCode, date, name } = req.body;
    let deterSql =
      "select * from ddetaillist where projectCode = ? and date = ? and name = ? ";
    pools.query(deterSql, [projectCode, date, name], (err, resl) => {
      if (err) {
        console.log(err, "error");
      } else {
        if (resl[0]) {
          resolve(false);
        } else {
          resolve(true);
        }
      }
    });
  });
};

//判断日期所填日期是否大于今天
const deterNow = (req) => {
  return new Promise((resolve, reject) => {
    let { date } = req.body;
    //获取今天的日期
    const currentDate = moment().format("YYYY-MM-DD");
    const res = moment(date).isBefore(moment(currentDate));
    const res1 = moment(date).isSame(moment(currentDate));
    if (res) {
      resolve(true);
    } else if (res1) {
      resolve(true);
    } else {
      resolve(false);
      return;
    }
  });
};

//判断当前时间是否大于或等于项目时间
const deterProjectDate = (req) => {
  console.log(req.body, "body");
  return new Promise((resolve, reject) => {
    let { projectCode, date, name } = req.body;
    let sql = "select startTime from projectlist where projectCode=?";
    let queryArr = [projectCode, name];
    let pools = mysql.createPool(env);
    pools.query(sql, queryArr, (err, result) => {
      if (err) {
        console.log(err);
      } else {
        console.log(result[0]["startTime"], "result");
        if (moment(result[0]["startTime"]).isSame(date)) {
          resolve(true);
        } else if (moment(result[0]["startTime"]).isBefore(date)) {
          resolve(true);
        } else {
          resolve(false);
        }
      }
    });
  });
};

const postmddetail = async (req, res) => {
  const deterP = await deterPerson(req);
  const deterD = await deterDate(req);
  const deterN = await deterNow(req);
  const deterPD = await deterProjectDate(req);
  //日报已填满
  if (!deterP) {
    res.send({
      code: 500,
      msg: "日报已填满",
    });
    return;
  }
  if (!deterD) {
    res.send({
      code: 500,
      msg: "该日期已填写",
    });
    return;
  }
  if (!deterN) {
    res.send({
      code: 500,
      msg: "日期只能选择当前日期之前的日期",
    });
    return;
  }
  if (!deterPD) {
    res.send({
      code: 500,
      msg: "该日期不在项目日期范围内",
    });
    return;
  }
  //提交
  console.log(req.body, "body");
  let { projectCode, content, date, name } = req.body;
  let pools = mysql.createPool(env);
  let queryArr = [projectCode, indexs(), content, date, name, "0"];
  pools.query(
    "insert into ddetaillist  values(?,?,?,?,?,?)",
    queryArr,
    (err, resk) => {
      if (err) {
        res.status(500);
        console.log(err);
      } else {
        if (resk.affectedRows >= 1) {
          res.send({
            code: 200,
            msg: "success",
          });
        } else {
          res.send({
            code: 500,
            msg: "error",
          });
        }
      }
    }
  );
};

router.post("/postmddetail", (req, res) => {
  postmddetail(req, res);
});

//删除日记

const deleteDdetail = (req, res) => {
  console.log(req.params.id);
  let sql = "delete from ddetaillist where id = ?";
  let queryArr = [req.params.id];
  let pools = mysql.createPool(env);
  pools.query(sql, queryArr, (err, result) => {
    if (err) {
      res.send({
        code: 500,
        msg: "语句问题",
      });
    } else {
      if (result.affectedRows == 1) {
        res.send({
          code: 200,
          msg: "success",
        });
        return;
      }
      res.send({
        code: 500,
        msg: "error",
      });
    }
  });
};
router.get("/deleteDdetail/:id", (req, res) => {
  deleteDdetail(req, res);
});

//编辑日记
//判断日期在范围内吗
const deterDate1 = (req) => {
  return new Promise((resolve, reject) => {
    let pools = mysql.createPool(env);
    let sql = "select startTime,endTime from projectlist where projectCode = ?";
    let queryArr = [req.body.projectCode];
    pools.query(sql, queryArr, (err, resy) => {
      if (err) {
        console.log(err + "error");
        resolve(false);
      } else {
        console.log(resy);
        let time = new Date(req.body.date).getTime();
        let time1 = new Date(resy[0]["startTime"]);
        let time2 = new Date(resy[0]["endTime"]);
        if (time >= time1 && time < time2) {
          resolve(true);
        } else {
          resolve(false);
        }
      }
    });
  });
};

const editDetail = async (req, res) => {
  const a = await deterDate1(req);
  if (!a) {
    res.send({
      code: 500,
      msg: "日期不在范围内",
    });
    return;
  }
  const arr = Object.keys(req.body);
  const queryArr = [];
  console.log(arr, "arr");
  let sql = "update ddetaillist set ";
  arr.forEach((ele, index) => {
    if (index != arr.length - 1) {
      sql += ele + " = ? , ";
      queryArr.push(req.body[ele]);
    } else {
      sql += ele + " = ? where projectCode = ?";
      queryArr.push(req.body[ele]);
      queryArr.push(req.body["projectCode"]);
    }
  });
  let pools = mysql.createPool(env);
  pools.query(sql, queryArr, (err, result) => {
    if (err) {
      res.status(500);
      console.log(err);
      res.send({
        code: 500,
        msg: "error",
      });
    } else {
      if (result.affectedRows == 1) {
        res.send({
          code: 200,
          msg: "success",
        });
      } else {
        res.send({
          code: 500,
          msg: "修改失败",
        });
      }
    }
  });
};

router.post("/editDetail", (req, res) => {
  editDetail(req, res);
});

//管理员查询管理日报

const afilters = (e) => {
  let objs = {};
  for (let keys in e) {
    if (
      e[keys] != "" &&
      e[keys] != undefined &&
      e[keys] != null &&
      keys != "pageNo" &&
      keys != "pageSize"
    ) {
      objs[keys] = e[keys];
    }
  }
  return Object.keys(objs);
};

const adminGetDaily = (req, res) => {
  const arrs = afilters(req.query);
  console.log(arrs, "arrs");
  let pools = mysql.createPool(env);
  let pageNo = Number(req.query["pageNo"]);
  let pageSize = Number(req.query["pageSize"]);
  let offset = (pageNo - 1) * pageSize;
  let sql = "select * from ddetaillist where ";
  let sqls = "select  count(*) from ddetaillist  where ";
  let queryArr = [];
  arrs.forEach((ele, ind) => {
    if (ind != arrs.length - 1) {
      sql += ` ${ele} = ? and `;
      sqls += ` ${ele} = ? and `;
      queryArr.push(req.query[ele]);
    } else {
      sql += ` ${ele} = ? limit ?,? `;
      sqls += ` ${ele} = ? `;
      queryArr.push(req.query[ele]);
    }
  });
  pools.query(sql, queryArr.concat([offset, pageSize]), (err, result) => {
    if (err) {
      res.status(500);
      console.log(err, "error");
    }
    pools.query(sqls, queryArr, (err, resl) => {
      console.log(resl, "resl");
      let total = 0;
      if (resl[0]) {
        total = resl[0]["count(*)"];
      }
      res.send({
        code: 200,
        msg: "success",
        data: {
          data: result,
          total: total,
        },
      });
    });
  });
};
router.get("/adminGetDaily", (req, res) => {
  adminGetDaily(req, res);
});

/* uni 获取日报列表 */

const getUser = () => {
  return new Promise((resolve, reject) => {
    let pools = mysql.createPool(env);
    let sql = "select * from userlist";
    pools.query(sql, [], (err, result) => {
      if (err) {
        console.log(err, "err");
        reject(err);
      } else {
        resolve(result);
      }
    });
  });
};
const uniMember = (req, res) => {
  let pools = mysql.createPool(env);
  if (req.query.id) {
    pools.query("select * from dtotallist", [], (err, result) => {
      if (err) {
        res.status(500);
        console.log(err, "error");
      } else {
        let arrs = [];
        result.forEach((el) => {
          if (el.member.indexOf(req.query.id) > -1) {
            arrs.push(el);
          }
        });
        res.send({
          code: 200,
          msg: "success",
          data: {
            data: arrs,
          },
        });
      }
    });
  } else {
    res.send({
      code: 500,
      msg: "查询条件id",
    });
  }
};
const uniAdmin = (req, res) => {
  let arrs = filters(req.query).filter((res) => {
    return res != "role";
  });
  let pools = mysql.createPool(env);
  if (arrs.length == 0) {
    let sql = "select * from dtotallist";
    pools.query(sql, [], async (err, result) => {
      if (err) {
        res.status(500);
        console.log(err, "error");
      } else {
        let data = await getUser();
        //result.member拆解
        result.forEach((ele) => {
          ele.memberArr = ele.member.split("/");
        });
        result.forEach((el) => {
          el.memberStr = "";
          el.memberArr.forEach((elk, index) => {
            data.forEach((elo) => {
              if (elo.id == elk) {
                el.memberStr += elo.name + "/";
              }
            });
          });
          el.memberStr = el.memberStr.slice(0, el.memberStr.length - 1);
        });
        res.send({
          code: 200,
          msg: "success",
          data: {
            data: result,
          },
        });
      }
    });
  } else {
    let sql = `select * from dtotallist where projectName like '%${req.query.projectName}%' `;
    pools.query(sql, [req.query.projectName], async (err, result) => {
      if (err) {
        res.status(500);
        console.log(err, "error");
      } else {
        let data = await getUser();
        //result.member拆解
        result.forEach((ele) => {
          ele.memberArr = ele.member.split("/");
        });
        result.forEach((el) => {
          el.memberStr = "";
          el.memberArr.forEach((elk, index) => {
            data.forEach((elo) => {
              if (elo.id == elk) {
                el.memberStr += elo.name + "/";
              }
            });
          });
          el.memberStr = el.memberStr.slice(0, el.memberStr.length - 1);
        });
        res.send({
          code: 200,
          msg: "success",
          data: {
            data: result,
          },
        });
      }
    });
  }
};
router.get("/uniGetDaily", (req, res) => {
  if (req.query.role == 0) {
    uniMember(req, res);
  } else {
    uniAdmin(req, res);
  }
});

/* uni 获取日报详情列表 */
const dailyMember = (req, res) => {
  let pools = mysql.createPool(env);
  const { name, projectCode } = req.query;
  let sql = "select * from ddetaillist where projectCode = ? and name = ?";
  pools.query(sql, [projectCode, name], (err, result) => {
    if (err) {
      res.status(500);
      console.log(err, "error");
    } else {
      res.send({
        code: 200,
        msg: "success",
        data: {
          data: result,
        },
      });
    }
  });
};
const dailyAdmin = (req, res) => {
  let pools = mysql.createPool(env);
  if (req.query.name == undefined || req.query.name == "") {
    console.log("全部查询");
    let sql = "select * from ddetaillist where projectCode = ? ";
    pools.query(sql, [req.query["projectCode"]], (err, resp) => {
      if (err) {
        res.status(500);
        console.log(err, "error");
      } else {
        res.send({
          code: 200,
          msg: "success",
          data: {
            data: resp,
          },
        });
      }
    });
  } else {
    let sql = "select * from ddetaillist where projectCode = ? and name = ?";
    pools.query(
      sql,
      [req.query["projectCode"], req.query["name"]],
      (err, result) => {
        if (err) {
          res.status(500);
          console.log(err, "err");
        } else {
          res.send({
            code: 200,
            msg: "success",
            data: {
              data: result,
            },
          });
        }
      }
    );
  }
};
router.get("/uniGetDailyList", (req, res) => {
  const { role } = req.query;
  if (role == 0) {
    dailyMember(req, res);
  } else {
    dailyAdmin(req, res);
  }
});

/* uni 获取日报选择器 */

const uniGetDailyUser = async (req, res) => {
  let datas = await getUser();
  let pools = mysql.createPool(env);
  pools.query(
    "select * from dtotallist where projectCode = ?",
    [req.query["projectCode"]],
    (err, resk) => {
      if (err) {
        res.status(500);
        console.log(err, "error");
      } else {
        let resArr = resk[0].member.split("/");
        let arr = [];
        console.log(resArr, "resArr");
        resArr.forEach((el, ind) => {
          datas.forEach((els, i) => {
            if (el == els.id) {
              let obj = {
                id: el,
                label: els.name,
              };
              arr.push(obj);
            }
          });
        });
        arr = [...[{ id: "0000000000", label: "清空" }], ...arr];
        res.send({
          code: 200,
          msg: "success",
          data: {
            data: arr,
          },
        });
      }
    }
  );
};

router.get("/uniGetDailyUser", (req, res) => {
  uniGetDailyUser(req, res);
});

module.exports = router;
